(function () {
  // 信息展示组件
  // eslint-disable-next-line max-lines-per-function
  const StockList = function (Vue) {
    let Scroller = null;
    const options = {
      props: [
        'list',
        'unit',
        'fixed',
        'expand',
        'menuHeight',
        'sortMethod',
        'fixedHead',
        'stockTag',
      ],
      data() {
        return {
          props: [],
          propKeys: {},
          showShadow: false,
          preExpandRow: null,
          showFixedHead: false,
          currentSortTag: 0,
          currentSortKey: null,
        };
      },
      mounted() {
        // eslint-disable-next-line no-use-before-define

        window.addEventListener(
          'scroll',
          save(evt => {
            // 由于左右滑动scroller会触发window的scroll,所以锁定页面滚动才触发以下函数
            if (evt.target !== document && !this.fixedHead) return;
            const { stockList } = this.$refs;
            const bdTop = stockList && stockList.getBoundingClientRect().top;
            this.showFixedHead = bdTop < 0;
            if (bdTop < 0 && this.fixedHead) {
              this.showFixedHead = true;
              this.$nextTick(() => {
                const { fixedHeadScroller } = this.$refs;
                const { stockListScroller } = this.$refs;
                fixedHeadScroller.scrollLeft = stockListScroller.scrollLeft;
              });
            } else {
              this.showFixedHead = false;
            }
          }),
          100
        );
      },
      watch: {
        /* 用于初始化横向滚动位置 */
        $route() {
          this.$nextTick(() => {
            const { stockListScroller } = this.$refs;
            stockListScroller.scrollLeft = 0;
            this.showShadow = false;
          });
        },
        stockTag() {
          this.$nextTick(() => {
            const { stockListScroller } = this.$refs;
            stockListScroller.scrollLeft = 0;
            this.showShadow = false;
          });
        },
      },
      methods: {
        sort(sortKey) {
          if (this.currentSortKey !== sortKey) {
            this.currentSortTag = 0;
          }
          this.currentSortKey = sortKey;
          this.currentSortTag++;
          if (this.currentSortTag === 1) {
            this.$emit('headSort', { sortKey, currentSortTag: this.currentSortTag });
          } else if (this.currentSortTag === 2) {
            this.$emit('headSort', { sortKey, currentSortTag: this.currentSortTag });
          } else {
            this.currentSortTag = 0;
            this.$emit('headSort', { sortKey, currentSortTag: this.currentSortTag });
          }
        },
      },
      // 列表组件
      render(h) {
        //展开收起事件
        const expandRow = row => {
          if (!this.expand) {
            this.$emit('clickRow', row);
            return;
          }
          if (this.preExpandRow && this.preExpandRow !== row) {
            this.preExpandRow.expand = false;
          }
          row.expand = !row.expand;
          this.preExpandRow = row;
        };
        //展开收起的插槽menu
        const menu = (scope, isShow) =>
          h(
            'div',
            {
              class: 'stock-list-menu',
              style: `${isShow ? 'position: relative;z-index:10;' : ''}; opacity: ${
                isShow ? '1' : '0'
              };`,
            },
            [
              this.$slots.default[0].data.scopedSlots &&
                this.$slots.default[0].data.scopedSlots.menu(scope),
            ]
          );
        // 左部头, 默认为第一列StockListItem
        const leftThead = h(
          'thead',
          {
            class: 'stock-list-lth',
          },
          [h('tr', {}, [this.$slots.default[0]])]
        );
        // 左部体, 默认为第一列StockListItem
        const leftTbody = this.list.map(row => {
          if (!this.props.length) return;
          let content = h('p', row[this.props[0].key]);
          // 如果有插槽就将插槽塞进去
          if (this.$slots.default[0].componentOptions.children) {
            content = this.$slots.default[0].componentOptions.children[0].data.scopedSlots.default(
              row
            );
          }
          // eslint-disable-next-line consistent-return
          return h(
            'tr',
            {
              on: {
                click: () => {
                  expandRow(row);
                },
              },
            },
            [
              h(
                'td',
                { class: 'tbody-font hxm-row-border', style: 'overflow-x: inherit' },
                row.expand ? [h('div', {}, [content]), menu(row, true)] : [h('div', {}, [content])]
              ),
            ]
          );
        });
        // 将写好的头和体塞进去
        const leftTable = h(
          'table',
          {
            class: ['stock-list-ltb', this.showShadow && 'stock-list-shadow'],
            style: `width: ${this.$slots.default[0].componentOptions.propsData.labelWidth}; display: flex; flex-direction: column;`,
          },
          [leftThead, h('tbody', {}, leftTbody)]
        );
        // 这句为啥这么处理 todo slot.tag 去表头项？？
        const rightSlots = this.$slots.default.filter((slot, index) => index && slot.tag);
        // 这里为什么要移除第一个 todo 去表头项？？
        const rightProps = this.$slots.default.slice(1);
        const rightThead = h(
          'thead',
          {
            class: 'stock-list-rth',
          },
          [h('tr', {}, rightSlots)]
        );
        const rightTableWidth = rightProps.reduce(
          (pre, next) => pre + parseFloat(next.componentOptions.propsData.labelWidth),
          0
        );
        const rightTbody = this.list.map(row => {
          const cells = rightSlots.map((slot, index) => {
            const key = rightProps[index] && rightProps[index].key;
            let content = h('p', row[key]);
            // 如果有插槽则将插槽塞入每行, 如果没有插槽则将<p>{{row[key]}}</>塞入插槽
            if (slot.componentOptions.children) {
              content = slot.componentOptions.children[0].data.scopedSlots.default(row);
            }
            //留出expand行的位置
            const currentColumn = this.$slots.default[index + 1].componentOptions.propsData;
            return h(
              'td',
              { class: 'tbody-font hxm-row-border', style: ` width: ${currentColumn.labelWidth};` },
              row.expand
                ? [
                    h(
                      'div',
                      {
                        style: `text-align: ${currentColumn.labelAlign};`,
                      },
                      [content]
                    ),
                    menu(row),
                  ]
                : [
                    h(
                      'div',
                      {
                        style: `text-align: ${
                          this.$slots.default[index + 1].componentOptions.propsData.labelAlign
                        };`,
                      },
                      [content]
                    ),
                  ]
            );
          });
          return h(
            'tr',
            {
              on: {
                click: () => {
                  expandRow(row);
                },
              },
            },
            cells
          );
        });
        // 将生成好的dom函数塞入
        const rightTable = h(
          'table',
          {
            class: 'stock-list-rtb',
            style: `width: ${rightTableWidth + (this.unit || 'rem')}`,
          },
          [rightThead, h('tbody', {}, rightTbody)]
        );
        // 生成吸顶头
        const fixedHead = h(
          'div',
          {
            class: ['stock-list stock-list-fixedhead sub-bg-card-one'],
            ref: 'fixedHead',
          },
          [
            h(
              'table',
              {
                class: ['stock-list-ltb', this.showShadow && 'stock-list-fixed-shadow'],
                style: 'margin-left:.32rem;',
              },
              [leftThead]
            ),
            h(
              'div',
              {
                class: 'stock-list-scroller',
                ref: 'fixedHeadScroller',
                style: 'margin-right:.32rem',
                on: {
                  scroll: evt => {
                    if (!Scroller) {
                      Scroller = evt.target;
                    } else if (Scroller !== evt.target) {
                      Scroller = null;
                      return;
                    }
                    const { scrollLeft } = evt.target;
                    const { stockListScroller } = this.$refs;
                    stockListScroller.scrollLeft = scrollLeft;
                    if (scrollLeft) {
                      this.showShadow = true;
                    } else {
                      this.showShadow = false;
                    }
                  },
                },
              },
              [
                h(
                  'table',
                  {
                    class: 'stock-list-rtb',
                    style: 'margin-left:.32rem',
                    style: `width: ${rightTableWidth + (this.unit || 'rem')}`,
                  },
                  [rightThead]
                ),
              ]
            ),
          ]
        );
        const bottomScope = h(
          'div',
          {
            class: '',
            ref: 'stockListScroller',
          },
          '查看更多'
        );
        // 这部分是？？
        const scroller = h(
          'div',
          {
            class: 'stock-list-scroller',
            ref: 'stockListScroller',
            on: {
              scroll: evt => {
                if (!Scroller) {
                  Scroller = evt.target;
                } else if (Scroller !== evt.target) {
                  Scroller = null;
                  return;
                }
                const { scrollLeft } = evt.target;
                if (this.showFixedHead) {
                  const { fixedHeadScroller } = this.$refs;
                  fixedHeadScroller.scrollLeft = scrollLeft;
                }
                if (scrollLeft) {
                  this.showShadow = true;
                } else {
                  this.showShadow = false;
                }
              },
            },
          },
          [rightTable]
        );
        const isScrollX =
          Number(rightTableWidth) +
            Number(this.$slots.default[0].componentOptions.propsData.labelWidth.split('rem')[0]) >
          6.86;
        const lookScrollIcon = h(
          'i',
          {
            class: 'icon-look-scroll',
            style: `display: ${this.showShadow ? 'none' : 'inline-block'}`,
          },
          ''
        );
        return h(
          'div',
          {
            class: ['stock-list sub-bg-card-one'],
            ref: 'stockList',
          },
          this.showFixedHead
            ? [fixedHead, leftTable, scroller, isScrollX && lookScrollIcon]
            : [leftTable, scroller, isScrollX && lookScrollIcon]
        );
      },
    };
    Vue.component('stock-list', options);
  };

  // 列表项
  const StockListItem = function (Vue) {
    const options = {
      props: ['prop', 'label', 'labelWidth', 'sortable', 'labelAlign', 'textWidth', 'paddingRight'],
      template: `
            <th :style="{width: labelWidth}" style="height: .72rem;" class=" hxm-row-border title-font">
              <div class="hxm-thead" @click="$parent.sort(prop)" :class="{hxmAlignLeft: labelAlign === 'left', hxmAlignRight: labelAlign === 'right'}">
                <p :style="{width: textWidth}">{{label}}</p>
                  <div class="stock-list-sort" :style="{paddingRight: paddingRight}" v-if="sortable">
                    <i class="icon-asc" v-if="$parent.currentSortKey === prop && $parent.currentSortTag === 1"></i>
                    <i class="icon-desc" v-else-if="$parent.currentSortKey === prop && $parent.currentSortTag === 2"></i>
                    <i class="icon-normal" v-else="$parent.currentSortTag == 0"></i>
                  </div>
              </div>
            </th>`,
      data() {
        return {};
      },
      methods: {
        /*sort(sortKey) {
          this.currentSortKey = sortKey;
          this.currentSortTag ++;
          if (this.currentSortTag === 1) {
            this.$parent.sort('ascending', this.prop);
          } else if(this.currentSortTag === 2){
            this.$parent.sort('dscending', this.prop);
          }else{
            this.currentSortTag = 0;
            this.$parent.sort('defaultending', this.prop);
          }
        }*/
      },
      mounted() {
        if (this.$parent.propKeys[this.prop]) return;
        this.$parent.propKeys[this.prop] = true;
        this.$parent.props.push({
          labelAlign: this.labelAlign,
          key: this.prop,
          label: this.label,
          labelWidth: this.labelWidth,
          sortable: this.sortable,
        });
      },
    };
    Vue.component('stock-list-item', options);
  };
  //暴露组件
  window._Components = {
    StockListItem,
    StockList,
  };
  // 节流
  function save(cb, time) {
    let timer;
    return function (...args) {
      if (timer) return;
      timer = setTimeout(function () {
        timer = null;
        cb(...args);
      }, time);
    };
  }
})();
